package net.kqinfo.core.controller.management;

import java.util.ArrayList;
import java.util.List;

import net.kqinfo.core.controller.management.condition.RoleCondition;
import net.kqinfo.core.model.Module;
import net.kqinfo.core.model.Role;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.render.DwzRender;
import com.jfinal.plugin.activerecord.Page;

public class RoleController extends Controller{
	
	private static final String CREATE = "/WEB-INF/views/management/security/role/create.html";
	private static final String UPDATE = "/WEB-INF/views/management/security/role/update.html";
	private static final String LIST = "/WEB-INF/views/management/security/role/list.html";
	private static final String VIEW = "/WEB-INF/views/management/security/role/view.html";
	
	public RoleCondition cond;
	
	public void view(){
		long id = getParaToLong(0, -1l);
		if (id == -1l) {
			render(DwzRender.error("请选择要查看的角色。"));
		}else{
			Role role = Role.dao.findById(id);
			setAttr("role", role);
		}
		setAttr("module", Module.dao.findById(1));
		render(VIEW);
	}
	
	@Before(RoleCondition.class)
	public void list(){
		StringBuilder sql = new StringBuilder();
		List<Object> paras = new ArrayList<Object>();
		cond.buildSql(sql, paras);
		Page<Role> page = Role.dao.paginate(cond.getPageNumber(), cond.getPageSize(), "select * ", sql.toString(), paras.toArray());
		setAttr("page", page);
		render(LIST);
	}
	
	public void create(){
		setAttr("module", Module.dao.findById(1));
		render(CREATE);
	}
	
	public void doCtreate(){
		Role role = getModel(Role.class);
		role.save();
		
		render(DwzRender.closeCurrentAndRefresh("page"));
	}
	
	public void update(){
		long id = getParaToLong(0, -1l);
		if (id == -1l) {
			render(DwzRender.error("请选择要编辑的角色。"));
		}else{
			Role role = Role.dao.findById(id);
			setAttr("role", role);
		}
		setAttr("module", Module.dao.findById(1));
		render(UPDATE);
	}
	
	public void doUpdate(){
		Role role = getModel(Role.class);
		role.update();
		render(DwzRender.closeCurrentAndRefresh("page"));
	}
	
	public void delete(){
		DwzRender.success();
	}

	public RoleCondition getCond() {
		return cond;
	}

	public void setCond(RoleCondition cond) {
		this.cond = cond;
	}
	
}
